package com.zy.community.framework.security.mini;

import com.zy.community.common.component.AesSecretComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
public class MiniSecurity {

    private final static Logger log = LoggerFactory.getLogger(MiniSecurity.class);
    @Resource
    private AesSecretComponent aesSecretComponent;

    public boolean check(Authentication authentication, HttpServletRequest request) {
        String miniToken = request.getHeader("miniToken");
        if (StringUtils.isEmpty(miniToken)) {
            return false;
        }
        try {
            String userinfo = aesSecretComponent.decrypt(miniToken);
            log.debug("小程序请求头鉴权:[{}]", userinfo);
            MiniContextUtils.setUserInfo(userinfo);
            return true;
        } catch (Exception e) {
            log.error("解密异常,token被篡改", e.getMessage());
            return false;
        }

    }
}
